#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "../../include/keyparse.h"

// 简单的日志回调函数
void log_callback(KeyParseLogLevel level, const char* message) {
    const char* level_str;
    switch (level) {
        case KEYPARSE_LOG_DEBUG: level_str = "DEBUG"; break;
        case KEYPARSE_LOG_INFO: level_str = "INFO"; break;
        case KEYPARSE_LOG_WARNING: level_str = "WARNING"; break;
        case KEYPARSE_LOG_ERROR: level_str = "ERROR"; break;
        default: level_str = "UNKNOWN"; break;
    }
    printf("[%s] %s\n", level_str, message);
}

void print_usage(const char* program_name) {
    printf("Usage: %s [OPTIONS] <input_file> [output_file]\n", program_name);
    printf("Options:\n");
    printf("  -h, --help          Show this help message\n");
    printf("  -v, --verbose       Enable verbose output\n");
    printf("  -s, --single        Process a single log line from command line\n");
    printf("  -d, --debug         Enable debug output\n");
    printf("\n");
    printf("Examples:\n");
    printf("  %s Linux_2k.log output.csv\n", program_name);
    printf("  %s -s \"Jun 17 20:34:57 combo sshd(pam_unix)[30631]: session closed for user test\"\n", program_name);
    printf("  %s -v -d Linux_2k.log output.csv\n", program_name);
}

int main(int argc, char* argv[]) {
    const char* input_file = NULL;
    const char* output_file = "parsing_results.csv";
    int verbose = 0;
    int debug = 0;
    int single_mode = 0;
    const char* single_log = NULL;
    
    // 解析命令行参数
    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
            print_usage(argv[0]);
            return 0;
        } else if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbose") == 0) {
            verbose = 1;
        } else if (strcmp(argv[i], "-d") == 0 || strcmp(argv[i], "--debug") == 0) {
            debug = 1;
        } else if (strcmp(argv[i], "-s") == 0 || strcmp(argv[i], "--single") == 0) {
            single_mode = 1;
            if (i + 1 < argc) {
                single_log = argv[++i];
            } else {
                fprintf(stderr, "Error: -s option requires a log line argument\n");
                return 1;
            }
        } else if (argv[i][0] == '-') {
            fprintf(stderr, "Error: Unknown option %s\n", argv[i]);
            print_usage(argv[0]);
            return 1;
        } else {
            // 位置参数
            if (!input_file) {
                input_file = argv[i];
            } else if (!output_file || strcmp(output_file, "parsing_results.csv") == 0) {
                // 只有当输出文件还是默认值时，才允许覆盖
                output_file = argv[i];
            } else {
                fprintf(stderr, "Error: Too many arguments\n");
                print_usage(argv[0]);
                return 1;
            }
        }
    }
    
    // 验证参数
    if (single_mode) {
        if (!single_log) {
            fprintf(stderr, "Error: Log line is required in single mode\n");
            print_usage(argv[0]);
            return 1;
        }
        // 在单条模式下，忽略输入文件和输出文件参数
        input_file = NULL;
        output_file = NULL;
    } else if (!input_file) {
        fprintf(stderr, "Error: Input file is required in batch mode\n");
        print_usage(argv[0]);
        return 1;
    }
    
    // 初始化KeyParse
    KeyParseHandle handle = keyparse_init();
    if (!handle) {
        fprintf(stderr, "Failed to initialize KeyParse\n");
        return 1;
    }
    
    // 设置日志回调
    if (verbose || debug) {
        keyparse_set_log_callback(log_callback);
    }
    
    time_t start_time = time(NULL);
    if (verbose) {
        printf("Start time: %s", ctime(&start_time));
    }
    
    int result = 0;
    
    if (single_mode) {
        // 单条日志模式
        char* group_key = NULL;
        char* template_str = NULL;
        
        KeyParseError ret = keyparse_process(handle, single_log, &group_key, &template_str);
        
        if (ret == KEYPARSE_SUCCESS) {
            printf("Group Key: %s\n", group_key);
            printf("Template: %s\n", template_str);
            
            // 释放内存
            keyparse_free_string(group_key);
            keyparse_free_string(template_str);
        } else {
            fprintf(stderr, "Failed to process log line: %s\n", keyparse_error_message(ret));
            result = 1;
        }
    } else {
        // 批量处理模式
        if (verbose) {
            printf("Processing log file: %s\n", input_file);
            printf("Output CSV file: %s\n", output_file);
        }
        
        int processed_count = keyparse_process_file(handle, input_file, output_file);
        
        if (processed_count >= 0) {
            if (verbose) {
                printf("Successfully processed %d log entries\n", processed_count);
                printf("Output saved to %s\n", output_file);
            }
        } else {
            fprintf(stderr, "Failed to process file\n");
            result = 1;
        }
    }
    
    time_t end_time = time(NULL);
    if (verbose) {
        printf("End time: %s", ctime(&end_time));
        printf("Elapsed time: %.2f seconds\n", difftime(end_time, start_time));
    }
    
    // 清理资源
    keyparse_free(handle);
    
    return result;
}